package dao

import (
	"yundian/internel/app/helper"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/models/agentincome"
	"yundian/internel/app/models/placeincome"
	"yundian/internel/app/models/users"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
	"yundian/internel/pkg/utils"
)

// 代理商统计

type AgentCountDao struct {
}

func NewAgentCountDao() *AgentCountDao {
	return &AgentCountDao{}
}

// 获取代理商某一天的交易总额
func (agentDao *AgentCountDao) GetAgentTotalMoney(userId, day int, sharedMode string) *dingo.ErrorWrap {
	var total int64
	userIdArr := NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)
	//查询是否可以抽单
	isDraw := NewUserDao().GetUserIsDraw(userId).Unwrap().(int)

	isDrawSql := ""
	if isDraw == 2 {
		isDrawSql = ` and is_draw = 0 `
	}

	if userId == 2 {
		sql := `SELECT IFNULL(SUM(settlement_money),0) as total FROM orders WHERE 
DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') = date_sub(curdate(), interval ? day) and shared_mode = ? and state = 5 ` + isDrawSql
		db := global.Orm.Debug().Raw(sql, day, sharedMode).Find(&total)
		return dingo.ErrorIf(db.Error, total)
	}

	//	if userId == 217 {
	//		placesBranchIds := NewUserDao().GetPlacesId(userId).Unwrap().([]int)
	//
	//		//获取直属或下级网点Id
	//		userIdArr := NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)
	//		placeIdArr := NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)
	//
	//		//合并网点
	//		placesBranchIds = append(placesBranchIds, placeIdArr...)
	//
	//		//去重网点
	//		placesIds := utils.RemoveRepByMap(placesBranchIds)
	//		sql := `SELECT IFNULL(SUM(settlement_money),0) as total FROM orders WHERE
	//DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') = date_sub(curdate(), interval ? day) and shared_mode = ? and state = 5 ` + isDrawSql + ` and is_tianhai = 0 and place_id in (?) `
	//		db := global.Orm.Debug().Raw(sql, day, sharedMode, placesIds).Find(&total)
	//		return dingo.ErrorIf(db.Error, total)
	//	}

	if len(userIdArr) > 0 {
		//userIdArr = append(userIdArr, userId)
		//placeModelLst := NewPlaceDao().GetPlaceByParentIds(userIdArr).Unwrap().([]*placemodel.PlaceModel)
		//placeIdArr := make([]int, 0)
		//for _, placeModel := range placeModelLst {
		//	placeIdArr = append(placeIdArr, placeModel.Id)
		//}
		placeIdArr := NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)
		if len(placeIdArr) <= 0 {
			return dingo.ErrorIf(nil, total)
		}
		sql := `SELECT IFNULL(SUM(settlement_money),0) as total FROM orders WHERE 
DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') = date_sub(curdate(), interval ? day) and shared_mode = ? and state = 5 ` + isDrawSql + ` and is_tianhai = 0 and place_id in (?) `
		db := global.Orm.Debug().Raw(sql, day, sharedMode, placeIdArr).Find(&total)
		return dingo.ErrorIf(db.Error, total)
	} else {
		sql := `SELECT IFNULL(SUM(settlement_money),0) as total FROM orders WHERE agent_user_id = ? and 
DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') = date_sub(curdate(), interval ? day) and shared_mode = ? and state = 5 ` + isDrawSql + `  and is_tianhai = 0`
		db := global.Orm.Raw(sql, userId, day, sharedMode).Find(&total)
		return dingo.ErrorIf(db.Error, total)
	}

}

func (agentDao *AgentCountDao) GetAgentTotalMoneyByDate(userId int, sharedMode, dateStr string) *dingo.ErrorWrap {
	var total int64
	userIdArr := NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)
	//查询是否可以抽单
	isDraw := NewUserDao().GetUserIsDraw(userId).Unwrap().(int)

	isDrawSql := ""
	if isDraw == 2 {
		isDrawSql = ` and is_draw = 0 `
	}

	if len(userIdArr) > 0 {
		//userIdArr = append(userIdArr, userId)
		//placeModelLst := NewPlaceDao().GetPlaceByParentIds(userIdArr).Unwrap().([]*placemodel.PlaceModel)
		//placeIdArr := make([]int, 0)
		//for _, placeModel := range placeModelLst {
		//	placeIdArr = append(placeIdArr, placeModel.Id)
		//}
		placeIdArr := NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)
		if len(placeIdArr) <= 0 {
			return dingo.ErrorIf(nil, total)
		}
		sql := `SELECT IFNULL(SUM(settlement_money),0) as total FROM orders WHERE 
DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') = ? and shared_mode = ? and state = 5 ` + isDrawSql + ` and is_tianhai = 0 and place_id in (?) `
		db := global.Orm.Debug().Raw(sql, dateStr, sharedMode, placeIdArr).Find(&total)
		return dingo.ErrorIf(db.Error, total)
	} else {
		sql := `SELECT IFNULL(SUM(settlement_money),0) as total FROM orders WHERE agent_user_id = ? and 
DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') = ? and shared_mode = ? and state = 5 ` + isDrawSql + `  and is_tianhai = 0`
		db := global.Orm.Raw(sql, userId, dateStr, sharedMode).Find(&total)
		return dingo.ErrorIf(db.Error, total)
	}

}

// 获取代理商某一天的交易订单数
func (agentDao *AgentCountDao) GetAgentTotalOrder(userId, day int, sharedMode string) *dingo.ErrorWrap {
	var count int64
	sql := `SELECT count(1) as total FROM orders WHERE agent_user_id = ? and 
DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') = date_sub(curdate(), interval ? day) and shared_mode = ? and is_tianhai = 0`
	db := global.Orm.Raw(sql, userId, day, sharedMode).Find(&count)
	return dingo.ErrorIf(db.Error, count)
}

// 获取代理商某一天的抽单总额
func (agentDao *AgentCountDao) GetAgentTotalMoneyByDraw(userId, day int, sharedMode string) *dingo.ErrorWrap {
	var total int64

	//查询是否可以抽单
	isDraw := NewUserDao().GetUserIsDraw(userId).Unwrap().(int)

	isDrawSql := ""
	if isDraw == 2 {
		isDrawSql = ` and is_draw = 0 `
	}

	sql := `SELECT IFNULL(SUM(settlement_money),0) as total FROM orders WHERE agent_user_id = ? and 
DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') = date_sub(curdate(), interval ? day) and shared_mode = ? and state = 5 ` + isDrawSql + ` and is_tianhai = 0 and is_draw = 1`
	db := global.Orm.Raw(sql, userId, day, sharedMode).Find(&total)
	return dingo.ErrorIf(db.Error, total)
}

// 获取代理商某一天的抽单订单数  (状态需要是已完成的!!!!)
func (agentDao *AgentCountDao) GetAgentTotalDrawCount(userId, day int, sharedMode string) *dingo.ErrorWrap {
	var count int64
	//查询是否可以抽单
	isDraw := NewUserDao().GetUserIsDraw(userId).Unwrap().(int)

	isDrawSql := ""
	if isDraw == 2 {
		isDrawSql = ` and is_draw = 0 `
	}

	sql := `SELECT count(1) as total FROM orders WHERE agent_user_id = ? and 
DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') = date_sub(curdate(), interval ? day) and shared_mode = ? and state = 5 ` + isDrawSql + ` and is_tianhai = 0 and is_draw = 1`
	db := global.Orm.Raw(sql, userId, day, sharedMode).Find(&count)
	return dingo.ErrorIf(db.Error, count)
}

// 获取代理商某一天的创建订单数
func (agentDao *AgentCountDao) GetAgentTotalOrderByCreate(userId, day int, sharedMode string) *dingo.ErrorWrap {
	var count int64

	//查询是否可以抽单
	isDraw := NewUserDao().GetUserIsDraw(userId).Unwrap().(int)

	isDrawSql := ""
	if isDraw == 2 {
		isDrawSql = ` and is_draw = 0 `
	}

	if userId == 2 {
		sql := `SELECT count(1) as total FROM orders WHERE 
DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') = date_sub(curdate(), interval ? day) and shared_mode = ? ` + isDrawSql
		db := global.Orm.Debug().Raw(sql, day, sharedMode).Find(&count)
		return dingo.ErrorIf(db.Error, count)
	}

	userIdArr := NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)
	if len(userIdArr) > 0 {
		//userIdArr = append(userIdArr, userId)
		//placeModelLst := NewPlaceDao().GetPlaceByParentIds(userIdArr).Unwrap().([]*placemodel.PlaceModel)
		//placeIdArr := make([]int, 0)
		//for _, placeModel := range placeModelLst {
		//	placeIdArr = append(placeIdArr, placeModel.Id)
		//}
		placeIdArr := NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)
		sql := `SELECT count(1) as total FROM orders WHERE 
DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') = date_sub(curdate(), interval ? day) and shared_mode = ? ` + isDrawSql + `  and is_tianhai = 0 and place_id in (?)`
		db := global.Orm.Raw(sql, day, sharedMode, placeIdArr).Find(&count)
		return dingo.ErrorIf(db.Error, count)

	} else {
		sql := `SELECT count(1) as total FROM orders WHERE agent_user_id = ? and 
DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') = date_sub(curdate(), interval ? day) and shared_mode = ? ` + isDrawSql + `  and is_tianhai = 0`
		db := global.Orm.Raw(sql, userId, day, sharedMode).Find(&count)
		return dingo.ErrorIf(db.Error, count)
	}

}

func (agentDao *AgentCountDao) GetAgentTotalOrderByCreateByDate(userId int, sharedMode, dateStr string) *dingo.ErrorWrap {
	var count int64
	userIdArr := NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)

	//查询是否可以抽单
	isDraw := NewUserDao().GetUserIsDraw(userId).Unwrap().(int)

	isDrawSql := ""
	if isDraw == 2 {
		isDrawSql = ` and is_draw = 0 `
	}

	if len(userIdArr) > 0 {
		//userIdArr = append(userIdArr, userId)
		//placeModelLst := NewPlaceDao().GetPlaceByParentIds(userIdArr).Unwrap().([]*placemodel.PlaceModel)
		//placeIdArr := make([]int, 0)
		//for _, placeModel := range placeModelLst {
		//	placeIdArr = append(placeIdArr, placeModel.Id)
		//}
		placeIdArr := NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)
		sql := `SELECT count(1) as total FROM orders WHERE 
DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') = ? and shared_mode = ? ` + isDrawSql + `  and is_tianhai = 0 and place_id in (?)`
		db := global.Orm.Raw(sql, dateStr, sharedMode, placeIdArr).Find(&count)
		return dingo.ErrorIf(db.Error, count)

	} else {
		sql := `SELECT count(1) as total FROM orders WHERE agent_user_id = ? and 
DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') = ? and shared_mode = ? ` + isDrawSql + `  and is_tianhai = 0`
		db := global.Orm.Raw(sql, userId, dateStr, sharedMode).Find(&count)
		return dingo.ErrorIf(db.Error, count)
	}

}

// 获取代理商某一天的订单数  state 2服务中  3撤销订单 5已完成订单 7待守约订单
func (agentDao *AgentCountDao) GetAgentTotalOrderCount(userId, day, state int, sharedMode string) *dingo.ErrorWrap {
	var count int64

	//查询是否可以抽单
	isDraw := NewUserDao().GetUserIsDraw(userId).Unwrap().(int)

	isDrawSql := ""
	if isDraw == 2 {
		isDrawSql = ` and is_draw = 0 `
	}
	if userId == 2 {
		sql := `SELECT count(1) as total FROM orders WHERE
DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') = date_sub(curdate(), interval ? day) and state = ? ` + isDrawSql
		db := global.Orm.Raw(sql, day, state, sharedMode).Find(&count)
		return dingo.ErrorIf(db.Error, count)
	}

	userIdArr := NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)
	if len(userIdArr) > 0 {
		//placeModelLst := NewPlaceDao().GetPlaceByParentIds(userIdArr).Unwrap().([]*placemodel.PlaceModel)
		//placeIdArr := make([]int, 0)
		//for _, placeModel := range placeModelLst {
		//	placeIdArr = append(placeIdArr, placeModel.Id)
		//}
		placeIdArr := NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)
		sql := `SELECT count(1) as total FROM orders WHERE
DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') = date_sub(curdate(), interval ? day) and state = ? ` + isDrawSql + `  and shared_mode = ? and is_tianhai = 0 and place_id in (?)`
		db := global.Orm.Raw(sql, day, state, sharedMode, placeIdArr).Find(&count)
		return dingo.ErrorIf(db.Error, count)

	} else {
		sql := `SELECT count(1) as total FROM orders WHERE agent_user_id = ? and 
DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') = date_sub(curdate(), interval ? day) and state = ? ` + isDrawSql + `  and shared_mode = ? and is_tianhai = 0`
		db := global.Orm.Raw(sql, userId, day, state, sharedMode).Find(&count)
		return dingo.ErrorIf(db.Error, count)
	}

}

func (agentDao *AgentCountDao) GetAgentTotalOrderCountByDate(userId, state int, sharedMode, dateStr string) *dingo.ErrorWrap {
	var count int64
	userIdArr := NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)

	//查询是否可以抽单
	isDraw := NewUserDao().GetUserIsDraw(userId).Unwrap().(int)

	isDrawSql := ""
	if isDraw == 2 {
		isDrawSql = ` and is_draw = 0 `
	}
	if len(userIdArr) > 0 {
		//placeModelLst := NewPlaceDao().GetPlaceByParentIds(userIdArr).Unwrap().([]*placemodel.PlaceModel)
		//placeIdArr := make([]int, 0)
		//for _, placeModel := range placeModelLst {
		//	placeIdArr = append(placeIdArr, placeModel.Id)
		//}
		placeIdArr := NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)
		sql := `SELECT count(1) as total FROM orders WHERE
DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') = ? and state = ? ` + isDrawSql + `  and shared_mode = ? and is_tianhai = 0 and place_id in (?)`
		db := global.Orm.Raw(sql, dateStr, state, sharedMode, placeIdArr).Find(&count)
		return dingo.ErrorIf(db.Error, count)

	} else {
		sql := `SELECT count(1) as total FROM orders WHERE agent_user_id = ? and 
DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') = ? and state = ? ` + isDrawSql + `  and shared_mode = ? and is_tianhai = 0`
		db := global.Orm.Raw(sql, userId, dateStr, state, sharedMode).Find(&count)
		return dingo.ErrorIf(db.Error, count)
	}

}

// 获取代理商的分红金额
func (agentDao *AgentCountDao) GetAgentIncome(userId, day int, sharedMode string) *dingo.ErrorWrap {
	var total int64
	userIdArr := NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)
	placeIdArr := NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)
	//查询是否可以抽单
	isDraw := NewUserDao().GetUserIsDraw(userId).Unwrap().(int)
	isDrawSql := ""
	if isDraw == 2 {
		isDrawSql = ` and is_draw = 0 `
	}

	//	sql := `SELECT IFNULL(SUM(money),0) as total FROM dividends_log WHERE user_id = ? and
	//DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') = date_sub(curdate(), interval ? day)  and shared_mode = ? and is_tianhai = 0`

	sql := ` SELECT IFNULL(SUM(money),0) FROM dividends_log WHERE trade_no IN (SELECT trade_no FROM orders WHERE place_id in(?) 
	and DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') = date_sub(curdate(), interval ? day)  and state = 5 ` + isDrawSql + ` ) and shared_mode = ? and is_tianhai = 0 AND user_id=? `

	db := global.Orm.Raw(sql, placeIdArr, day, sharedMode, userId).Find(&total)
	return dingo.ErrorIf(db.Error, total)
}

// 获取代理商的分红金额
func (agentDao *AgentCountDao) GetAgentIncomeInfo(userId int, day string) *dingo.ErrorWrap {
	var dbInfo []*agentincome.AgentIncomeModel

	db := global.Orm.Where("agent_user_id=? AND income_day=?", userId, day)
	db.Find(&dbInfo)
	return dingo.ErrorIf(db.Error, dbInfo)
}

func (agentDao *AgentCountDao) GetAgentIncomeNoDraw(userId, day int, sharedMode string) *dingo.ErrorWrap {
	var total int64
	sql := `SELECT IFNULL(SUM(money),0) as total FROM dividends_log WHERE user_id = ? and
	DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') = date_sub(curdate(), interval ? day)  and shared_mode = ? and is_tianhai = 0`

	db := global.Orm.Raw(sql, userId, day, sharedMode).Find(&total)
	return dingo.ErrorIf(db.Error, total)
}

func (agentDao *AgentCountDao) GetAgentIncomeNoDrawByDate(userId int, sharedMode, dateStr string) *dingo.ErrorWrap {
	var total int64
	sql := `SELECT IFNULL(SUM(money),0) as total FROM dividends_log WHERE user_id = ? and
	DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') = ?  and shared_mode = ? and is_tianhai = 0`

	db := global.Orm.Raw(sql, userId, dateStr, sharedMode).Find(&total)
	return dingo.ErrorIf(db.Error, total)
}

// 查找是否统计过
func (agentDao *AgentCountDao) CountAgentIncomeInfo(userId int, d, sharedMode string) *dingo.ErrorWrap {
	var count int64
	sql := `SELECT count(1) FROM agent_income WHERE agent_user_id = ? and income_day = ? and shared_mode = ?`
	db := global.Orm.Raw(sql, userId, d, sharedMode).Find(&count)
	return dingo.ErrorIf(db.Error, count)
}

// 查找是否统计过
func (agentDao *AgentCountDao) CountBranchIncomeInfo(userId int, d, sharedMode string) *dingo.ErrorWrap {
	var count int64
	sql := `SELECT count(1) FROM branch_income WHERE agent_user_id = ? and income_day = ? and shared_mode = ?`
	db := global.Orm.Raw(sql, userId, d, sharedMode).Find(&count)
	return dingo.ErrorIf(db.Error, count)
}

// 新增统计
func (agentDao *AgentCountDao) InsertAgentIncomeInfo(m *agentincome.AgentIncomeModel) *dingo.ErrorWrap {
	db := global.Orm.Table("agent_income").Create(m)
	return dingo.ErrorIf(db.Error, true)
}

// 修改统计
func (agentDao *AgentCountDao) UpdateAgentIncomeInfo(m *agentincome.AgentIncomeModel) *dingo.ErrorWrap {

	sql := `UPDATE agent_income SET income_day = ?,total_money=?,draw_money= ?,draw_count= ?,divinds_money= ?,trade_total = ?,shared_mode = ?,order_count = ?,cancel_count = ?,complete_count = ?,agent_user_id = ?,agent_user_name = ?,user_no =?,phone =?,name =?,places_total =?,device_total =?  WHERE agent_user_id = ? AND income_day = ? AND shared_mode = ?`
	db := global.Orm.Debug().Exec(sql, m.IncomeDay, m.TotalMoney, m.DrawMoney, m.DrawCount, m.DivindsMoney, m.TradeTotal, m.SharedMode, m.OrderCount, m.CancelCount, m.CompleteCount, m.AgentUserId,
		m.AgentUserName, m.UserNo, m.Phone, m.Name, m.PlacesTotal, m.DeviceTotal, m.AgentUserId, m.IncomeDay, m.SharedMode)
	return dingo.ErrorIf(db.Error, true)
}

// 不修改网点的统计
func (agentDao *AgentCountDao) UpdateAgentCancelPlaceInfo(m *agentincome.AgentIncomeModel) *dingo.ErrorWrap {

	sql := `UPDATE agent_income SET income_day = ?,total_money=?,draw_money= ?,draw_count= ?,divinds_money= ?,trade_total = ?,shared_mode = ?,order_count = ?,cancel_count = ?,complete_count = ?,agent_user_id = ?,agent_user_name = ?,user_no =?,phone =?,name =?,device_total =?  WHERE agent_user_id = ? AND income_day = ? AND shared_mode = ?`
	db := global.Orm.Debug().Exec(sql, m.IncomeDay, m.TotalMoney, m.DrawMoney, m.DrawCount, m.DivindsMoney, m.TradeTotal, m.SharedMode, m.OrderCount, m.CancelCount, m.CompleteCount, m.AgentUserId,
		m.AgentUserName, m.UserNo, m.Phone, m.Name, m.DeviceTotal, m.AgentUserId, m.IncomeDay, m.SharedMode)
	return dingo.ErrorIf(db.Error, true)
}

// 新增统计
func (agentDao *AgentCountDao) InsertBranchIncomeInfo(m *agentincome.BranchIncomeModel) *dingo.ErrorWrap {
	db := global.Orm.Table("branch_income").Create(m)
	return dingo.ErrorIf(db.Error, true)
}

func (agentDao *AgentCountDao) UpdateBranchIncomeInfo(m *agentincome.BranchIncomeModel) *dingo.ErrorWrap {
	//db := global.Orm.Debug().Table("branch_income").
	//	Where("agent_user_id = ?", m.BranchUserId).
	//	Where("income_day = ?", m.IncomeDay).
	//	Where("shared_mode = ?", m.SharedMode).
	//	Model(&m).Updates(m)

	sql := `UPDATE branch_income SET income_day = ?,total_money=?,draw_money= ?,draw_count= ?,divinds_money= ?,trade_total = ?,shared_mode = ?,order_count = ?,cancel_count = ?,complete_count = ?,agent_user_id = ?,agent_user_name = ?,user_no =?,phone =?,name =?,places_total =?,device_total =?  WHERE agent_user_id = ? AND income_day = ? AND shared_mode = ?`
	db := global.Orm.Debug().Exec(sql, m.IncomeDay, m.TotalMoney, m.DrawMoney, m.DrawCount, m.DivindsMoney, m.TradeTotal, m.SharedMode, m.OrderCount, m.CancelCount, m.CompleteCount, m.BranchUserId,
		m.BranchUserName, m.UserNo, m.Phone, m.Name, m.PlacesTotal, m.DeviceTotal, m.BranchUserId, m.IncomeDay, m.SharedMode)
	return dingo.ErrorIf(db.Error, true)
}

// 查询 代理商的每日收益
func (agentDao *AgentCountDao) GetAgentIncomeList(param *request.AgentIncomeListReq, userId int) *dingo.ErrorWrap {
	var (
		lst    []agentincome.AgentIncomeModel
		count  int64
		limit  int = param.PageSize
		offset int = param.PageSize * (param.PageNo - 1)
	)

	fields := `SUM(dl.money)total_money,SUM(o.settlement_money)trade_total,dl.user_id agent_user_id,DATE_FORMAT(dl.end_date, '%Y-%m-%d') income_day`
	db := global.Orm.Debug().Table("dividends_log dl").Select(fields).Joins("LEFT JOIN orders o ON dl.trade_no=o.trade_no")
	db.Where("dl.user_id=?", userId)
	db.Where("dl.end_date>?", "1970-01-01")

	if param.IsAdmin != helper.TypeNumIsAdminOperator {
		//if param.IsDraw != helper.TypeNumIsDrawOpen {
		//	db.Where("o.is_draw<>? or o.agent_user_id=?", helper.TypeNumIsDrawOpen, userId)
		//} else {
		//	db.Where("o.is_draw<>? or (o.is_draw=? and o.agent_user_id=?)", helper.TypeNumIsDrawOpen, helper.TypeNumIsDrawOpen, userId)
		//}
		db.Where("o.is_draw<>? or (o.is_draw=? and o.agent_user_id=?)", helper.TypeNumIsDrawOpen, helper.TypeNumIsDrawOpen, userId)
		db.Where("o.is_tianhai = 0")
	}

	db.Group("dl.end_date").Order("dl.end_date DESC")
	db.Limit(limit).Offset(offset).Find(&lst).Limit(-1).Offset(-1).Count(&count)

	return dingo.ErrorIf(db.Error, lst, count)

}

//查询旗下的网点
func (agentDao *AgentCountDao) GetPlacesTotal(userId int) *dingo.ErrorWrap {
	var placesTotal int64
	if userId == 2 {
		sql := "select count(id) from places"
		db := global.Orm.Raw(sql).Find(&placesTotal)
		return dingo.ErrorIf(db.Error, placesTotal)
	}

	if userId == 217 || userId == 219 || userId == 221 {
		placesBranchIds := NewUserDao().GetPlacesId(userId).Unwrap().([]int)
		//userIds := dao.NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)
		//获取直属或下级网点Id
		userIdArr := NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)
		placeIdArr := NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)

		//合并网点
		placesBranchIds = append(placesBranchIds, placeIdArr...)

		//去重网点
		placesIds := utils.RemoveRepByMap(placesBranchIds)
		placesTotal = int64(len(placesIds))
		return dingo.ErrorIf(nil, placesTotal)
	}

	userIdArr := NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)
	userIdArr = append(userIdArr, userId)

	sql := "select count(p.id) as placesTotal from places p LEFT JOIN users u on p.user_id = u.id WHERE u.id IN ?"
	db := global.Orm.Raw(sql, userIdArr).Find(&placesTotal)
	return dingo.ErrorIf(db.Error, placesTotal)
}

//查询旗下的设备总数
func (agentDao *AgentCountDao) GetDeviceTotal(userId int) *dingo.ErrorWrap {
	var deviceTotal int64
	if userId == 2 {
		sql := "SELECT count(1) from devices where state != 1 "
		db := global.Orm.Raw(sql).Find(&deviceTotal)
		return dingo.ErrorIf(db.Error, deviceTotal)
	}

	if userId == 217 || userId == 219 || userId == 221 {
		placesBranchIds := NewUserDao().GetPlacesId(userId).Unwrap().([]int)
		//userIds := dao.NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)
		//获取直属或下级网点Id
		userIdArr := NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)
		placeIdArr := NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)

		//合并网点
		placesBranchIds = append(placesBranchIds, placeIdArr...)

		//去重网点
		placesIds := utils.RemoveRepByMap(placesBranchIds)
		deviceTotal = int64(len(placesIds))
		sql := "SELECT count(1) from devices where state != 1 AND place_id in (?)"
		db := global.Orm.Raw(sql, placesIds).Find(&deviceTotal)
		return dingo.ErrorIf(db.Error, deviceTotal)
	}

	userIdArr := NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)
	placeIdArr := NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)

	if len(placeIdArr) <= 0 {
		return dingo.ErrorIf(nil, deviceTotal)
	}
	sql := "SELECT count(1) from devices where state != 1 AND place_id in (?)"
	db := global.Orm.Raw(sql, placeIdArr).Find(&deviceTotal)
	return dingo.ErrorIf(db.Error, deviceTotal)
}

//----------分公司操作
// 获取代理商某一天的抽单总额
func (agentDao *AgentCountDao) GetBranchTotalMoneyByDraw(placesIds []int, day int, sharedMode string) *dingo.ErrorWrap {
	var total int64
	sql := `SELECT IFNULL(SUM(settlement_money),0) as total FROM orders WHERE  place_id in (?) and 
DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') = date_sub(curdate(), interval ? day) and shared_mode = ? and state = 5 and is_tianhai = 0 and is_draw = 1`
	db := global.Orm.Raw(sql, placesIds, day, sharedMode).Find(&total)
	return dingo.ErrorIf(db.Error, total)
}

// 获取分公司某一天的交易总额
func (agentDao *AgentCountDao) GetBranchTotalMoney(userId, day int, sharedMode string) *dingo.ErrorWrap {
	var total int64
	//分公司获取关联的网点Id
	placesBranchIds := NewUserDao().GetPlacesId(userId).Unwrap().([]int)

	//获取直属或下级网点Id
	userIdArr := NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)
	placeIdArr := NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)

	//合并网点
	placesBranchIds = append(placesBranchIds, placeIdArr...)

	//去重网点
	placesIds := utils.RemoveRepByMap(placesBranchIds)

	isDraw := NewUserDao().GetUserIsDraw(userId).Unwrap().(int)

	isDrawSql := ""
	if isDraw == 2 {
		isDrawSql = ` and is_draw = 0 `
	}

	if len(placesIds) > 0 {
		sql := `SELECT IFNULL(SUM(settlement_money),0) as total FROM orders WHERE 
DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') = date_sub(curdate(), interval ? day) and shared_mode = ? and state = 5 ` + isDrawSql + ` and is_tianhai = 0 and place_id in (?) `
		db := global.Orm.Debug().Raw(sql, day, sharedMode, placesIds).Find(&total)
		return dingo.ErrorIf(db.Error, total)
	} else {
		sql := `SELECT IFNULL(SUM(settlement_money),0) as total FROM orders WHERE user_id in (?) and 
DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') = date_sub(curdate(), interval ? day) and shared_mode = ? and state = 5  ` + isDrawSql + ` and is_tianhai = 0`
		db := global.Orm.Raw(sql, placesIds, day, sharedMode).Find(&total)
		return dingo.ErrorIf(db.Error, total)
	}

}

// 获取分公司某一天的创建订单数
func (agentDao *AgentCountDao) GetBranchTotalOrderByCreate(userId, day int, sharedMode string) *dingo.ErrorWrap {
	var count int64

	//分公司获取关联的网点Id
	placesBranchIds := NewUserDao().GetPlacesId(userId).Unwrap().([]int)

	//获取直属或下级网点Id
	userIdArr := NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)
	placeIdArr := NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)

	//合并网点
	placesBranchIds = append(placesBranchIds, placeIdArr...)

	//去重网点
	placesIds := utils.RemoveRepByMap(placesBranchIds)

	//查询是否可以抽单

	isDraw := NewUserDao().GetUserIsDraw(userId).Unwrap().(int)

	isDrawSql := ""
	if isDraw == 2 {
		isDrawSql = ` and is_draw = 0 `
	}

	if len(placesIds) > 0 {
		sql := `SELECT count(1) as total FROM orders WHERE 
DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') = date_sub(curdate(), interval ? day) and shared_mode = ? ` + isDrawSql + `  and is_tianhai = 0 and place_id in (?)`
		db := global.Orm.Raw(sql, day, sharedMode, placesIds).Find(&count)
		return dingo.ErrorIf(db.Error, count)

	} else {
		sql := `SELECT count(1) as total FROM orders WHERE agent_user_id = ? and 
DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') = date_sub(curdate(), interval ? day) and shared_mode = ? ` + isDrawSql + `  and is_tianhai = 0`
		db := global.Orm.Raw(sql, userId, day, sharedMode).Find(&count)
		return dingo.ErrorIf(db.Error, count)
	}

}

// 获取分公司某一天的订单数  state 2服务中  3撤销订单 5已完成订单 7待守约订单
func (agentDao *AgentCountDao) GetBranchTotalOrderCount(userId, day, state int, sharedMode string) *dingo.ErrorWrap {
	var count int64
	//分公司获取关联的网点Id
	placesBranchIds := NewUserDao().GetPlacesId(userId).Unwrap().([]int)

	//获取直属或下级网点Id
	userIdArr := NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)
	placeIdArr := NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)

	//合并网点
	placesBranchIds = append(placesBranchIds, placeIdArr...)

	//去重网点
	placesIds := utils.RemoveRepByMap(placesBranchIds)

	//查询是否可以抽单
	isDraw := NewUserDao().GetUserIsDraw(userId).Unwrap().(int)

	isDrawSql := ""
	if isDraw == 2 {
		isDrawSql = ` and is_draw = 0 `
	}

	if len(placesIds) > 0 {

		sql := `SELECT count(1) as total FROM orders WHERE
DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') = date_sub(curdate(), interval ? day) and state = ? and shared_mode = ? ` + isDrawSql + `  and is_tianhai = 0 and place_id in (?)`
		db := global.Orm.Debug().Raw(sql, day, state, sharedMode, placesIds).Find(&count)
		return dingo.ErrorIf(db.Error, count)

	} else {
		sql := `SELECT count(1) as total FROM orders WHERE agent_user_id = ? and 
DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') = date_sub(curdate(), interval ? day) and state = ? and shared_mode = ? ` + isDrawSql + `  and is_tianhai = 0`
		db := global.Orm.Raw(sql, userId, day, state, sharedMode).Find(&count)
		return dingo.ErrorIf(db.Error, count)
	}

}

//查询旗下的网点
func (agentDao *AgentCountDao) GetBranchPlacesTotal(userId int) *dingo.ErrorWrap {

	var placesTotal int64
	//分公司获取关联的网点Id
	placesBranchIds := NewUserDao().GetPlacesId(userId).Unwrap().([]int)

	//获取直属或下级网点Id
	userIdArr := NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)
	placeIdArr := NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)

	//合并网点
	placesBranchIds = append(placesBranchIds, placeIdArr...)

	//去重网点
	placesIds := utils.RemoveRepByMap(placesBranchIds)

	placesTotal = int64(len(placesIds))
	return dingo.ErrorIf(nil, placesTotal)
}

//查询旗下的设备总数
func (agentDao *AgentCountDao) GetBranchDeviceTotal(userId int) *dingo.ErrorWrap {
	//分公司获取关联的网点Id
	placesBranchIds := NewUserDao().GetPlacesId(userId).Unwrap().([]int)

	//获取直属或下级网点Id
	userIdArr := NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)
	placeIdArr := NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)

	//合并网点
	placesBranchIds = append(placesBranchIds, placeIdArr...)

	//去重网点
	placesIds := utils.RemoveRepByMap(placesBranchIds)
	var deviceTotal int64
	if len(placesIds) <= 0 {
		return dingo.ErrorIf(nil, deviceTotal)
	}
	sql := "SELECT count(id) from devices where state != 1 AND place_id in (?)"
	db := global.Orm.Raw(sql, placesIds).Find(&deviceTotal)
	return dingo.ErrorIf(db.Error, deviceTotal)
}

//--------网点

func (agentDao *AgentCountDao) GetPlaceTotalMoneyByDraw(placesId int, day int, sharedMode string) *dingo.ErrorWrap {
	var total int64
	sql := `SELECT IFNULL(SUM(settlement_money),0) as total FROM orders WHERE  place_id = ? and 
DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') = date_sub(curdate(), interval ? day) and shared_mode = ? and state = 5 and is_draw = 0 and is_tianhai = 0 `
	db := global.Orm.Raw(sql, placesId, day, sharedMode).Find(&total)
	return dingo.ErrorIf(db.Error, total)
}

func (agentDao *AgentCountDao) GetAPlaceIncome(placesId, userId, day int, sharedMode string) *dingo.ErrorWrap {
	var total int64

	//查询是否可以抽单
	isDraw := NewUserDao().GetUserIsDraw(userId).Unwrap().(int)
	isDrawSql := ""
	if isDraw == 2 {
		isDrawSql = ` and is_draw = 0 `
	}

	//sql := `SELECT IFNULL(SUM(money),0) as total FROM dividends_log WHERE place_id = ? and user_id = ?  and DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') = date_sub(curdate(), interval ? day) and shared_mode = ? and is_tianhai = 0`
	sql := `SELECT IFNULL(SUM(money),0) as total FROM dividends_log WHERE trade_no IN (SELECT trade_no FROM orders WHERE place_id = ? 
	and DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') = date_sub(curdate(), interval ? day) and state = 5 ` + isDrawSql + ` ) and shared_mode = ? and is_tianhai = 0 AND user_id=? `
	db := global.Orm.Raw(sql, placesId, day, sharedMode, userId).Find(&total)
	return dingo.ErrorIf(db.Error, total)
}

func (agentDao *AgentCountDao) GetAPlaceIncomeNoDraw(placesId, userId, day int, sharedMode string) *dingo.ErrorWrap {

	var total int64
	sql := `SELECT IFNULL(SUM(money),0) as total FROM dividends_log WHERE user_id = ? and place_id = ? and 
	DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') = date_sub(curdate(), interval ? day)  and shared_mode = ?`

	db := global.Orm.Raw(sql, userId, placesId, day, sharedMode).Find(&total)
	return dingo.ErrorIf(db.Error, total)
}

// 获取分公司某一天的创建订单数
func (agentDao *AgentCountDao) GetPlaceTotalOrderByCreate(placesId, day int, sharedMode string) *dingo.ErrorWrap {
	var count int64

	sql := `SELECT count(1) as total FROM orders WHERE place_id = ? and 
DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') = date_sub(curdate(), interval ? day) and shared_mode = ?  and is_draw = 0 and is_tianhai = 0`
	db := global.Orm.Raw(sql, placesId, day, sharedMode).Find(&count)
	return dingo.ErrorIf(db.Error, count)

}

// 获取分公司某一天的订单数  state 2服务中  3撤销订单 5已完成订单 7待守约订单
func (agentDao *AgentCountDao) GetPlaceTotalOrderCount(placesId, day, state int, sharedMode string) *dingo.ErrorWrap {
	var count int64

	sql := `SELECT count(1) as total FROM orders WHERE place_id = ? and 
DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') = date_sub(curdate(), interval ? day) and state = ?  and is_draw = 0 and shared_mode = ? and is_tianhai = 0`
	db := global.Orm.Raw(sql, placesId, day, state, sharedMode).Find(&count)
	return dingo.ErrorIf(db.Error, count)

}

//查询旗下的设备总数
func (agentDao *AgentCountDao) GetPlaceDeviceTotal(placesId int) *dingo.ErrorWrap {
	var deviceTotal int64
	sql := "SELECT count(id) from devices where state != 1 AND place_id = ?"
	db := global.Orm.Raw(sql, placesId).Find(&deviceTotal)
	return dingo.ErrorIf(db.Error, deviceTotal)
}

// 查找是否统计过
func (agentDao *AgentCountDao) CountPlaceIncomeInfo(placesId int, d, sharedMode string) *dingo.ErrorWrap {
	var count int64
	sql := `SELECT count(1) FROM place_income WHERE place_id = ? and income_day = ? and shared_mode = ?`
	db := global.Orm.Raw(sql, placesId, d, sharedMode).Find(&count)
	return dingo.ErrorIf(db.Error, count)
}

func (agentDao *AgentCountDao) UpdatePlaceIncomeInfo(m *placeincome.PlaceIncomeModel) *dingo.ErrorWrap {

	sql := `UPDATE place_income SET place_id = ?,place_name=?,place_create_at= ?,settlement_money= ?,order_count= ?,income_day = ?,income = ?,shared_mode = ?,agent_user_id = ?,cancel_count = ?,complete_count = ?,device_total = ? WHERE place_id = ? AND income_day = ? AND shared_mode = ?`
	db := global.Orm.Exec(sql, m.PlaceId, m.PlaceName, m.PlaceCreateAt, m.SettlementMoney, m.OrderCount, m.IncomeDay, m.Income, m.SharedMode, m.AgentUserId, m.CancelCount, m.CompleteCount,
		m.DeviceTotal, m.PlaceId, m.IncomeDay, m.SharedMode)
	return dingo.ErrorIf(db.Error, true)
}

// 新增统计
func (agentDao *AgentCountDao) InsertPlaceIncomeInfo(m *placeincome.PlaceIncomeModel) *dingo.ErrorWrap {
	db := global.Orm.Table("place_income").Create(m)
	return dingo.ErrorIf(db.Error, true)
}

//------------分开代理商执行的sql
// 获取代理商某一天的交易总额
func (agentDao *AgentCountDao) GetSeparateAgentTotalMoney(userId int, day, sharedMode string) *dingo.ErrorWrap {
	var total int64
	userIdArr := NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)
	//查询是否可以抽单
	isDraw := NewUserDao().GetUserIsDraw(userId).Unwrap().(int)

	isDrawSql := ""
	if isDraw == 2 {
		isDrawSql = ` and is_draw = 0 `
	}

	if len(userIdArr) > 0 {
		//userIdArr = append(userIdArr, userId)
		//placeModelLst := NewPlaceDao().GetPlaceByParentIds(userIdArr).Unwrap().([]*placemodel.PlaceModel)
		//placeIdArr := make([]int, 0)
		//for _, placeModel := range placeModelLst {
		//	placeIdArr = append(placeIdArr, placeModel.Id)
		//}
		placeIdArr := NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)
		if len(placeIdArr) <= 0 {
			return dingo.ErrorIf(nil, total)
		}
		sql := `SELECT IFNULL(SUM(settlement_money),0) as total FROM orders WHERE 
DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') = ? and shared_mode = ? and state = 5 ` + isDrawSql + ` and is_tianhai = 0 and place_id in (?) `
		db := global.Orm.Debug().Raw(sql, day, sharedMode, placeIdArr).Find(&total)
		return dingo.ErrorIf(db.Error, total)
	} else {
		sql := `SELECT IFNULL(SUM(settlement_money),0) as total FROM orders WHERE agent_user_id = ? and 
DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') = ? and shared_mode = ? and state = 5 ` + isDrawSql + `  and is_tianhai = 0`
		db := global.Orm.Raw(sql, userId, day, sharedMode).Find(&total)
		return dingo.ErrorIf(db.Error, total)
	}

}

//优化代理商金额查询
func (d *PlaceDao) GetAgentMoneyByDate(userIds []int, date, sharedMode string) *dingo.ErrorWrap {
	var agentSettlementMoney []users.AgentSettlementMoney
	isDrawMap := make(map[int]int)
	isDrawList := NewUserDao().GetUserIsDrawByUserIds(userIds).Unwrap().([]users.AgentUserIsDraw)

	for _, v := range isDrawList {
		isDrawMap[v.UsersId] = v.IsDraw
	}

	var isDrawUserId, notIsDrawUserId []int
	//是否有抽单权限分组
	for _, id := range userIds {
		if _, ok := isDrawMap[id]; ok {
			isDrawUserId = append(isDrawUserId, id)
		} else {
			notIsDrawUserId = append(notIsDrawUserId, id)
		}
	}

	db := global.Orm
	//查询统计金额
	var isDrawMoney []users.AgentSettlementMoney
	if len(isDrawUserId) > 0 {

		sql := `SELECT IFNULL(SUM(settlement_money),0) as total,agent_user_id as user_id ,DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') as date FROM orders WHERE agent_user_id in(?) and 
DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') = ? and shared_mode = ? and state = 5 and is_draw = 1  and is_tianhai = 0  GROUP BY user_id,date `
		db.Raw(sql, isDrawUserId, date, sharedMode).Find(&isDrawMoney)
	} else {
		sql := `SELECT IFNULL(SUM(settlement_money),0) as total,agent_user_id as user_id ,DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') as date FROM orders WHERE agent_user_id in(?) and 
DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') = ? and shared_mode = ? and state = 5 and is_draw != 1  and is_tianhai = 0  GROUP BY user_id,date `
		db.Raw(sql, notIsDrawUserId, date, sharedMode).Find(&agentSettlementMoney)
	}
	//合并切片
	agentSettlementMoney = append(agentSettlementMoney, isDrawMoney...)
	return dingo.ErrorIf(db.Error, agentSettlementMoney)
}

//代理商分红
func (d *PlaceDao) GetAgentDividendsByDate(userIds []int, date, sharedMode string) *dingo.ErrorWrap {
	var agentDividends []users.AgentDividendsModel
	sql := `SELECT IFNULL(SUM(money),0) as user_money,user_id,DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') as date FROM dividends_log WHERE  user_id in(?) AND DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') = ?  and shared_mode = ? GROUP BY user_id,date `
	db := global.Orm.Debug().Raw(sql, userIds, date, sharedMode).Find(&agentDividends)
	return dingo.ErrorIf(db.Error, agentDividends)
}

//代理商查询订单
func (d *PlaceDao) GetAgentTotalOrderByDate(userIds []int, date, sharedMode string) *dingo.ErrorWrap {
	var agentTotalOrder []users.AgentTotalOrder
	isDrawMap := make(map[int]int)
	isDrawList := NewUserDao().GetUserIsDrawByUserIds(userIds).Unwrap().([]users.AgentUserIsDraw)

	for _, v := range isDrawList {
		isDrawMap[v.UsersId] = v.IsDraw
	}

	var isDrawUserId, notIsDrawUserId []int
	//是否有抽单权限分组
	for _, id := range userIds {
		if _, ok := isDrawMap[id]; ok {
			isDrawUserId = append(isDrawUserId, id)
		} else {
			notIsDrawUserId = append(notIsDrawUserId, id)
		}
	}

	db := global.Orm
	//查询统计金额
	var isDrawTotalOrder []users.AgentTotalOrder
	if len(isDrawUserId) > 0 {
		sql := `SELECT count(1) as total FROM orders WHERE agent_user_id in (?) and DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') = ?  
				and shared_mode = ? and is_draw = 1  and is_tianhai = 0 `
		db.Raw(sql, isDrawUserId, date, sharedMode).Find(&isDrawTotalOrder)
	} else {
		sql := `SELECT count(1) as total FROM orders WHERE agent_user_id in (?) and DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') = ?  
				and shared_mode = ? and is_draw != 1 and is_tianhai = 0 `
		db.Raw(sql, notIsDrawUserId, date, sharedMode).Find(&agentTotalOrder)
	}
	//合并切片
	agentTotalOrder = append(agentTotalOrder, isDrawTotalOrder...)
	return dingo.ErrorIf(db.Error, agentTotalOrder)
}

func (d *PlaceDao) GetAgentTotalOrderStateByDate(userIds []int, state int, date, sharedMode string) *dingo.ErrorWrap {
	var agentTotalOrder []users.AgentTotalOrder
	isDrawMap := make(map[int]int)
	isDrawList := NewUserDao().GetUserIsDrawByUserIds(userIds).Unwrap().([]users.AgentUserIsDraw)

	for _, v := range isDrawList {
		isDrawMap[v.UsersId] = v.IsDraw
	}

	var isDrawUserId, notIsDrawUserId []int
	//是否有抽单权限分组
	for _, id := range userIds {
		if _, ok := isDrawMap[id]; ok {
			isDrawUserId = append(isDrawUserId, id)
		} else {
			notIsDrawUserId = append(notIsDrawUserId, id)
		}
	}

	db := global.Orm
	//查询统计金额
	var isDrawTotalOrder []users.AgentTotalOrder
	if len(isDrawUserId) > 0 {
		sql := `SELECT count(1) as total FROM orders WHERE agent_user_id in (?) and state = ?  and DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') = ?  
				and shared_mode = ? and is_draw = 1  and is_tianhai = 0 `
		db.Raw(sql, isDrawUserId, state, date, sharedMode).Find(&isDrawTotalOrder)
	} else {
		sql := `SELECT count(1) as total FROM orders WHERE agent_user_id in (?) and state = ?  and DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') = ?  
				and shared_mode = ? and is_draw != 1 and is_tianhai = 0 `
		db.Raw(sql, notIsDrawUserId, state, date, sharedMode).Find(&agentTotalOrder)
	}
	//合并切片
	agentTotalOrder = append(agentTotalOrder, isDrawTotalOrder...)
	return dingo.ErrorIf(db.Error, agentTotalOrder)
}

func (agentDao *AgentCountDao) GetSeparateAgentIncomeNoDraw(userId int, day, sharedMode string) *dingo.ErrorWrap {
	var total int64
	sql := `SELECT IFNULL(SUM(money),0) as total FROM dividends_log WHERE user_id = ? and
	DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') = ?  and shared_mode = ? and is_tianhai = 0`

	db := global.Orm.Raw(sql, userId, day, sharedMode).Find(&total)
	return dingo.ErrorIf(db.Error, total)
}

// 获取代理商某一天的创建订单数
func (agentDao *AgentCountDao) GetSeparateAgentTotalOrderByCreate(userId int, day, sharedMode string) *dingo.ErrorWrap {
	var count int64
	userIdArr := NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)

	//查询是否可以抽单
	isDraw := NewUserDao().GetUserIsDraw(userId).Unwrap().(int)

	isDrawSql := ""
	if isDraw == 2 {
		isDrawSql = ` and is_draw = 0 `
	}

	if len(userIdArr) > 0 {
		//userIdArr = append(userIdArr, userId)
		//placeModelLst := NewPlaceDao().GetPlaceByParentIds(userIdArr).Unwrap().([]*placemodel.PlaceModel)
		//placeIdArr := make([]int, 0)
		//for _, placeModel := range placeModelLst {
		//	placeIdArr = append(placeIdArr, placeModel.Id)
		//}
		placeIdArr := NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)
		sql := `SELECT count(1) as total FROM orders WHERE 
DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') = ? and shared_mode = ? ` + isDrawSql + `  and is_tianhai = 0 and place_id in (?)`
		db := global.Orm.Raw(sql, day, sharedMode, placeIdArr).Find(&count)
		return dingo.ErrorIf(db.Error, count)

	} else {
		sql := `SELECT count(1) as total FROM orders WHERE agent_user_id = ? and 
DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') = ? and shared_mode = ? ` + isDrawSql + `  and is_tianhai = 0`
		db := global.Orm.Raw(sql, userId, day, sharedMode).Find(&count)
		return dingo.ErrorIf(db.Error, count)
	}

}

// 获取代理商某一天的订单数  state 2服务中  3撤销订单 5已完成订单 7待守约订单
func (agentDao *AgentCountDao) GetSeparateAgentTotalOrderCount(userId, state int, day, sharedMode string) *dingo.ErrorWrap {
	var count int64
	userIdArr := NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)

	//查询是否可以抽单
	isDraw := NewUserDao().GetUserIsDraw(userId).Unwrap().(int)

	isDrawSql := ""
	if isDraw == 2 {
		isDrawSql = ` and is_draw = 0 `
	}
	if len(userIdArr) > 0 {
		//placeModelLst := NewPlaceDao().GetPlaceByParentIds(userIdArr).Unwrap().([]*placemodel.PlaceModel)
		//placeIdArr := make([]int, 0)
		//for _, placeModel := range placeModelLst {
		//	placeIdArr = append(placeIdArr, placeModel.Id)
		//}
		placeIdArr := NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)
		sql := `SELECT count(1) as total FROM orders WHERE
DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') = ? and state = ? ` + isDrawSql + `  and shared_mode = ? and is_tianhai = 0 and place_id in (?)`
		db := global.Orm.Raw(sql, day, state, sharedMode, placeIdArr).Find(&count)
		return dingo.ErrorIf(db.Error, count)

	} else {
		sql := `SELECT count(1) as total FROM orders WHERE agent_user_id = ? and 
DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') = ? and state = ? ` + isDrawSql + `  and shared_mode = ? and is_tianhai = 0`
		db := global.Orm.Raw(sql, userId, day, state, sharedMode).Find(&count)
		return dingo.ErrorIf(db.Error, count)
	}

}

//------------分开执行的网点SQL

func (agentDao *AgentCountDao) GetSeparatePlaceTotalMoney(placesId []int, day string, sharedMode string) *dingo.ErrorWrap {

	var separatePlaceTotalMoney []placeincome.SeparatePlaceTotal
	sql := `SELECT IFNULL(SUM(settlement_money),0) as total,DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') as date,place_id FROM orders WHERE  place_id in (?) and 
DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') = ? and shared_mode = ? and state = 5 and is_draw != 1  and is_tianhai = 0 GROUP BY place_id`
	db := global.Orm.Raw(sql, placesId, day, sharedMode).Find(&separatePlaceTotalMoney)
	return dingo.ErrorIf(db.Error, separatePlaceTotalMoney)
}

func (agentDao *AgentCountDao) GetSeparatePlaceTotalOrder(placesId []int, day string, sharedMode string) *dingo.ErrorWrap {
	var separatePlaceTotalOrder []placeincome.SeparatePlaceTotal

	sql := `SELECT count(1) as total,DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') as date,place_id FROM orders WHERE place_id in (?) and 
DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') = ? and shared_mode = ?  and is_draw != 1 and is_tianhai = 0 GROUP BY place_id`
	db := global.Orm.Debug().Raw(sql, placesId, day, sharedMode).Find(&separatePlaceTotalOrder)
	return dingo.ErrorIf(db.Error, separatePlaceTotalOrder)

}

// 获取分公司某一天的订单数  state 2服务中  3撤销订单 5已完成订单 7待守约订单
func (agentDao *AgentCountDao) GetSeparatePlaceTotalOrderComplete(state int, placesId []int, day, sharedMode string) *dingo.ErrorWrap {
	var separatePlaceOrderComplete []placeincome.SeparatePlaceTotal

	sql := `SELECT count(1) as total,DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') as date,place_id  FROM orders WHERE place_id in(?) and 
DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') = ? and state = ?  and is_draw != 1 and shared_mode = ? and is_tianhai = 0 GROUP BY place_id`
	db := global.Orm.Raw(sql, placesId, day, state, sharedMode).Find(&separatePlaceOrderComplete)
	return dingo.ErrorIf(db.Error, separatePlaceOrderComplete)

}

// 查找是否统计过
func (agentDao *AgentCountDao) SeparateCountPlaceIncomeInfo(placesId []int, day, sharedMode string) *dingo.ErrorWrap {
	var separatePlaceOrderComplete []placeincome.SeparatePlaceTotal
	sql := `SELECT count(1) as total,income_day as date,place_id FROM place_income WHERE place_id in (?) and income_day = ? and shared_mode = ? GROUP BY place_id`
	db := global.Orm.Raw(sql, placesId, day, sharedMode).Find(&separatePlaceOrderComplete)
	return dingo.ErrorIf(db.Error, separatePlaceOrderComplete)
}

func (agentDao *AgentCountDao) GetSeparatePlaceTotalMoneyByDraw(placesId int, day string, sharedMode string) *dingo.ErrorWrap {

	var total int64
	sql := `SELECT IFNULL(SUM(settlement_money),0) as total FROM orders WHERE  place_id = ? and 
DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') = ? and shared_mode = ? and state = 5 and is_draw != 1 and is_tianhai = 0 `
	db := global.Orm.Raw(sql, placesId, day, sharedMode).Find(&total)
	return dingo.ErrorIf(db.Error, total)
}

func (agentDao *AgentCountDao) GetSeparateAPlaceIncomeNoDraw(placesId, userId int, day string, sharedMode string) *dingo.ErrorWrap {

	var total int64
	sql := `SELECT IFNULL(SUM(money),0) as total FROM dividends_log WHERE user_id = ? and place_id = ? and 
	DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') = ?  and shared_mode = ?`

	db := global.Orm.Raw(sql, userId, placesId, day, sharedMode).Find(&total)
	return dingo.ErrorIf(db.Error, total)
}

// 获取分公司某一天的创建订单数
func (agentDao *AgentCountDao) GetSeparatePlaceTotalOrderByCreate(placesId int, day string, sharedMode string) *dingo.ErrorWrap {
	var count int64

	sql := `SELECT count(1) as total FROM orders WHERE place_id = ? and 
DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') = ? and shared_mode = ?  and is_draw = 0 and is_tianhai = 0`
	db := global.Orm.Raw(sql, placesId, day, sharedMode).Find(&count)
	return dingo.ErrorIf(db.Error, count)

}

// 获取分公司某一天的订单数  state 2服务中  3撤销订单 5已完成订单 7待守约订单
func (agentDao *AgentCountDao) GetSeparatePlaceTotalOrderCount(placesId, state int, day, sharedMode string) *dingo.ErrorWrap {
	var count int64

	sql := `SELECT count(1) as total FROM orders WHERE place_id = ? and 
DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') = ? and state = ?  and is_draw = 0 and shared_mode = ? and is_tianhai = 0`
	db := global.Orm.Raw(sql, placesId, day, state, sharedMode).Find(&count)
	return dingo.ErrorIf(db.Error, count)

}
